In this recipe we look at a new looping construct in JavaScript 1.2.Discussion
JavaScript and JavaScript 1.1 have already given you top-tested loops for scripting:// // A top-tested numerically-bounded loop // for(var i=0; i < 26; i++) document.write(i+' = '+alphabetString.charAt(i)+'<BR>')or// // A top-tested logically-bounded loop // var i = 0 while(i < 26) { document.write(i+' = '+alphabetString.charAt(i)+'<BR>') i++ }JavaScript 1.2 now makes a bottom-tested loop available, which is better suited for some kinds of scripting tasks. The syntax is
do { // // Task // } while(condition)where condition is any logical test you might apply to a while() or if() function.
A top-tested loop might keep the script from entering the loop code at all, and some scripting logic requires that you "prime the pump" by setting one or more variables to appropriate initial values (like in the second example above).
A bottom-tested loop will always execute at least once, and can avoid "pump priming" code.
Copyright ©2000 by Charles River Media, All Rights Reserved